package com.H1023.service;

import com.H1023.dao.TypeMapper;
import com.H1023.pojo.Pager;
import com.H1023.pojo.Type;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MJ
 * @date 2021/10/10 9:23
 */
public class TypeServiceImpl implements TypeService{

    @Autowired
    private TypeMapper typeMapper;

    public void setTypeMapper(TypeMapper typeMapper){
        this.typeMapper = typeMapper;
    }

    public List<Type> getAllType() {
        return typeMapper.getAllType();
    }

    public Type getTypeById(int id) {
        return typeMapper.getTypeById(id);
    }

    public Pager<Type> findByPager(String method, String order, int page, int size){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", (page-1)*size);
        map.put("size", size);
        map.put("order", order);
        map.put("method", method);
        Pager<Type> pager = new Pager<Type>();
        List<Type> list = typeMapper.findByPager(map);
        pager.setRows(list);
        pager.setTotal(typeMapper.count());
        return pager;
    }

    //刷新所用到的重写的方法
    public Pager<Type> findByPager(int page, int size){
        return findByPager(null,null,page,size);
    }

    public int addType(Type type){
        int a;  //插入返回的标志
        try {
            if (typeMapper.getTypeByName(type.getTypename())==1){
                System.out.println("已存在！！！");
                throw new Exception();
            }
            if (type.getTypename()==null){
                System.out.println("name为null！");
                throw new Exception();
            }
            a=typeMapper.addType(type);
        }catch (Exception e){
            System.out.println("插入失败！");
            a=-1;
        }
        return a;
    }

    public long count(){
        return typeMapper.count();
    }

    public int deleteType(int typeid){
        int i;
        try {
            i = typeMapper.deleteType(typeid);
            if (i==0)
                throw new Exception();
        }catch (Exception e){
            System.out.println("删除失败！");
            i=-1;
        }
        return i;
    }

    public int updateType(int typeid,String typename){
        int a;  //插入返回的标志
        try {
            if (typeMapper.getTypeByName(typename)==1){
                System.out.println("已存在！！！");
                throw new Exception();
            }
            if (typename==null){
                System.out.println("name为null！");
                throw new Exception();
            }
            a=typeMapper.updateType(new Type(typeid,typename));
        }catch (Exception e){
            System.out.println("修改失败！");
            a=-1;
        }
        return a;
    }

}
